package com.shwread.android.ui.page;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.utils.NetWorkUtils;
import com.ciko.code.utils.Util;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.task.AskPersonalTaskActivity;
import com.shwread.android.qysw.activity.task.OrganizationTaskDetailActivity;
import com.shwread.android.qysw.activity.task.PersonalTaskDetailActivity;
import com.shwread.android.qysw.activity.task.SearchTaskActivity;
import com.shwread.android.qysw.adapter.TaskAdapter;
import com.shwread.android.qysw.bean.task.TaskActBean;
import com.shwread.android.qysw.bean.task.TaskActBean.TaskActInfo;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.widget.refresh.SuperSwipeRefreshLayout;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;

/**
 * 任务管理
 */
public class TaskManagementPage extends AbstractUIPage<MainActivity> implements View.OnClickListener, TaskAdapter.ItemListener {
    private static TaskManagementPage instance;
    private static final int REQUEST_REFURBISH = 8;
    /**
     * 搜索
     */
    private LinearLayout llSearchKeyword;
    /**
     * 团体活动任务
     */
    private TextView tvOrganizationTask;
    /**
     * 个人申报任务
     */
    private TextView tvPersonalTask;
    /**
     * 活动列表
     */
    private RecyclerView rlvTaskList;
    /**
     * 申报活动任务
     */
    private TextView addTask;
    /**
     * 刷新控件
     */
    private SuperSwipeRefreshLayout layoutSwipeRefresh;
    // Header View
    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    // Footer View
    private ProgressBar footerProgressBar;
    private TextView footerTextView;
    private ImageView footerImageView;

    /**
     * 动画页面
     */
    private RelativeLayout commonLoadingLayout;
    /**
     * 加载动画
     */
    private ImageView loadingImg;
    /**
     * 动画
     */
    private AnimationDrawable animationDrawable;

    private TaskAdapter taskAdapter;
    private int type;
    private List<TaskActInfo> mData = new ArrayList<>();
    /**
     * 加载页码
     */
    private int page = 0;
    /**
     * 最后一次加载数据条数
     */
    private int data_num = 0;
    /**
     * 每页加载条目
     */
    private int page_num = 30;
    private Button btnBack;

    public static TaskManagementPage getInstance(MainActivity t) {
        if (null == instance) {
            instance = new TaskManagementPage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }

    private TaskManagementPage(MainActivity t) {
        super(t);
    }

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) {
            return curMyView;
        }
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.page_task_management, null);
        type = TaskAdapter.ORGANIZATION_TASK;
        initView();
        initData();
        initListener();
        return curMyView;
    }

    private void initView() {
        TextView tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText("任务管理");
        ImageView ivPersonal = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        ivPersonal.setVisibility(View.GONE);
        addTask = (TextView) curMyView.findViewById(R.id.common_header_create_team);
        addTask.setText("+申报活动任务");
        addTask.setTextSize(14);
        addTask.setVisibility(View.VISIBLE);
        btnBack = (Button) curMyView.findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);

        llSearchKeyword = (LinearLayout) curMyView.findViewById(R.id.ll_search_keyword);
        tvOrganizationTask = (TextView) curMyView.findViewById(R.id.tv_organization_task);
        tvOrganizationTask.setEnabled(false);
        tvPersonalTask = (TextView) curMyView.findViewById(R.id.tv_personal_task);
        rlvTaskList = (RecyclerView) curMyView.findViewById(R.id.rlv_task_list);
        loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);
        commonLoadingLayout = (RelativeLayout) curMyView.findViewById(R.id.common_loading_layout);

        layoutSwipeRefresh = (SuperSwipeRefreshLayout) curMyView.findViewById(R.id.layout_swipe_refresh);
        layoutSwipeRefresh.setHeaderView(createHeaderView());
        layoutSwipeRefresh.setFooterView(createFooterView());
    }

    private void initData() {
        taskAdapter = new TaskAdapter(mData, this);
        rlvTaskList.setAdapter(taskAdapter);
        getData(0);
    }

    private void initListener() {
        addTask.setOnClickListener(this);
        llSearchKeyword.setOnClickListener(this);
        tvOrganizationTask.setOnClickListener(this);
        tvPersonalTask.setOnClickListener(this);
        commonLoadingLayout.setOnClickListener(this);
        btnBack.setOnClickListener(this);

        layoutSwipeRefresh.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {//下拉刷新
            @Override
            public void onRefresh() {
                textView.setText("正在刷新");
                imageView.setVisibility(View.GONE);
                progressBar.setVisibility(View.VISIBLE);
                getData(1);
            }

            @Override
            public void onPullDistance(int distance) {
            }

            @Override
            public void onPullEnable(boolean enable) {
                textView.setText(enable ? "松开刷新" : "下拉刷新");
                imageView.setVisibility(View.VISIBLE);
                imageView.setRotation(enable ? 180 : 0);
            }
        });
        layoutSwipeRefresh.setOnPushLoadMoreListener(new SuperSwipeRefreshLayout.OnPushLoadMoreListener() {//上拉加载
            @Override
            public void onLoadMore() {
                if (data_num == page_num) {
                    footerTextView.setText("正在加载...");
                    footerImageView.setVisibility(View.GONE);
                    footerProgressBar.setVisibility(View.VISIBLE);
                    getData(2);
                } else {
                    footerTextView.setText("没有更多数据");
                    footerImageView.setVisibility(View.GONE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            footerImageView.setVisibility(View.VISIBLE);
                            layoutSwipeRefresh.setLoadMore(false);
                        }
                    }, 500);
                }
            }

            @Override
            public void onPushEnable(boolean enable) {
                footerTextView.setText(enable ? "松开加载" : "上拉加载");
                footerImageView.setVisibility(View.VISIBLE);
                footerImageView.setRotation(enable ? 0 : 180);
            }

            @Override
            public void onPushDistance(int distance) {
            }
        });
    }

    private View createHeaderView() {//设置头布局
        View headerView = LayoutInflater.from(layoutSwipeRefresh.getContext()).inflate(R.layout.layout_head, null);
        progressBar = (ProgressBar) headerView.findViewById(R.id.pb_view);
        textView = (TextView) headerView.findViewById(R.id.text_view);
        textView.setText("下拉刷新");
        imageView = (ImageView) headerView.findViewById(R.id.image_view);
        imageView.setVisibility(View.VISIBLE);
        imageView.setImageResource(R.drawable.xlistview_arrow);
        progressBar.setVisibility(View.GONE);
        return headerView;
    }

    private View createFooterView() {//设置脚布局
        View footerView = LayoutInflater.from(layoutSwipeRefresh.getContext()).inflate(R.layout.layout_footer, null);
        footerProgressBar = (ProgressBar) footerView.findViewById(R.id.footer_pb_view);
        footerImageView = (ImageView) footerView.findViewById(R.id.footer_image_view);
        footerTextView = (TextView) footerView.findViewById(R.id.footer_text_view);
        footerProgressBar.setVisibility(View.GONE);
        footerImageView.setVisibility(View.VISIBLE);
        footerImageView.setImageResource(R.drawable.xlistview_arrow);
        footerTextView.setText("上拉加载更多...");
        return footerView;
    }

    /**
     * 获取数据 0-初次加载,1-刷新,2-下拉加载
     */
    private void getData(final int status) {
        if (!NetWorkUtils.isConnected(bActivity)) {
            if (status == 0) {
                new NetworkDialog(bActivity).show();
            } else {
                Util.showToast(bActivity, "网络错误，请检查网络");
            }
            refurbish(false);
            return;
        }

        switch (status) {
            case 0:
                commonLoadingLayout.setVisibility(View.VISIBLE);
                commonLoadingLayout.setEnabled(false);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                page = 0;
                mData.clear();
                break;
            case 1:
                page = 0;
                mData.clear();
                break;
            case 2:
                page++;
                break;
        }
        NewActionHelp.qryPostActivityList(bActivity, page, page_num, null, type, new ObjectHttpResponseHandler<TaskActBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
                refurbish(false);
            }

            @Override
            public void onSuccess(int i, Header[] headers, TaskActBean taskActBean, String s) {
                Log.e("sss", "成功--" + s);
                if (taskActBean != null && taskActBean.getPostActivityInfos() != null) {
                    mData.addAll(taskActBean.getPostActivityInfos());
                } else {
                    Log.e("sss", "没有数据");
                }
                refurbish(true);
            }

            @Override
            public Type getType() {
                return new TypeToken<TaskActBean>() {
                }.getType();
            }
        });
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        if (arg0 == REQUEST_REFURBISH) {
            type = TaskAdapter.PERSONAL_TASK;
            TaskSwitch();
        }
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back://返回
                bActivity.onBackPressed();
                break;
            case R.id.common_header_create_team://申报活动任务
                Intent intent = new Intent(bActivity, AskPersonalTaskActivity.class);
                bActivity.startActivityForResult(intent, REQUEST_REFURBISH);
                break;
            case R.id.ll_search_keyword://关键词搜索
                intent2Acticity(SearchTaskActivity.class);
                break;
            case R.id.tv_organization_task://组织活动任务
                type = TaskAdapter.ORGANIZATION_TASK;
                TaskSwitch();
                break;
            case R.id.tv_personal_task://个人任务
                type = TaskAdapter.PERSONAL_TASK;
                TaskSwitch();
                break;
            case R.id.common_loading_layout://重新加载
                getData(0);
                break;
        }
    }

    /**
     * 任务切换
     */
    private void TaskSwitch() {
        NewActionHelp.cancel(bActivity);
        refurbish(true);
        tvOrganizationTask.setTextColor(bActivity.getResources()
                .getColor(type == TaskAdapter.ORGANIZATION_TASK ? R.color.color_cb1c1d : R.color.color_252525));
        tvPersonalTask.setTextColor(bActivity.getResources()
                .getColor(type == TaskAdapter.PERSONAL_TASK ? R.color.color_cb1c1d : R.color.color_252525));
        tvOrganizationTask.setEnabled(type != TaskAdapter.ORGANIZATION_TASK);
        tvPersonalTask.setEnabled(type != TaskAdapter.PERSONAL_TASK);
        getData(0);
    }

    @Override
    public void itemClick(TaskActInfo taskBean) {//列表点击事件
        Intent intent = new Intent();
        if (taskBean.getListType() == TaskAdapter.ORGANIZATION_TASK) {
            intent.setClass(bActivity, OrganizationTaskDetailActivity.class);
        } else if (taskBean.getListType() == TaskAdapter.PERSONAL_TASK) {
            intent.setClass(bActivity, PersonalTaskDetailActivity.class);
        }
        intent.putExtra("taskId", taskBean.getId());
        bActivity.startActivity(intent);
    }

    /**
     * 刷新
     */
    private void refurbish(boolean status) {
        footerImageView.setVisibility(View.VISIBLE);
        footerProgressBar.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
        layoutSwipeRefresh.setRefreshing(false);
        layoutSwipeRefresh.setLoadMore(false);

        taskAdapter.notifyData(mData);
        if (animationDrawable != null && animationDrawable.isRunning()) {
            animationDrawable.stop();
        }
        if (status) {//加载失败设置重新刷新
            commonLoadingLayout.setVisibility(View.GONE);
        } else {
            commonLoadingLayout.setVisibility(View.VISIBLE);
            commonLoadingLayout.setEnabled(true);
            loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
        }
    }
}
